import Vue from 'vue'
import Router from 'vue-router'

Vue.use(Router)

export const constantRoutes = [{
	path: '/',
	redirect: '/login'
}, {
	name: 'login',
	path: '/login',
	component: () => import('@/pages/login.vue')
}, {
	name: 'home',
	path: '/home',
	component: () => import('@/pages/home.vue'),
	redirect: '/welcome',
	children: [{
		name: 'welcome',
		path: '/welcome',
		component: () => import('@/pages/welcome.vue'),
	},{
		name: 'emplist',
		path: '/emplist',
		component: () => import('@/pages/emplist.vue'),
	},{
		name: 'demolab',
		path: '/demolab',
		component: () => import('@/pages/demolab.vue'),
	}]
}, ]

const createRouter = () => new Router({
	// mode: 'history', // require service support
	scrollBehavior: () => ({
		y: 0
	}),
	routes: constantRoutes
})

const router = createRouter()
//下面是设置路由守卫，未登录的不放行，直接跳登录页
router.beforeEach((to, from, next) => {
	// 访问登录页，放行
	if (to.path == '/login') return next()
	// 获取token
	const tokenStr = window.sessionStorage.getItem('token')
	// 没有token, 强制跳转到登录页
	if (!tokenStr) return next('/login')
	next()
})


// Detail see: https://github.com/vuejs/vue-router/issues/1234#issuecomment-357941465
export function resetRouter() {
	const newRouter = createRouter()
	router.matcher = newRouter.matcher // reset router
}

export default router
